/**
 * Created by Weilin Shi on 2015/10/6.
 */
/*jslint vars: true, forin:true, sloppy: true*/
/*global angular, probe*/
probe.service('scriptEngine', function (LC, LCP, LD) {
	var finishTime = 0, sourceCache, $recentError = null, $tree = null;

	var parse = function (code, option) {
		$recentError = null;
		sourceCache = code;

		try {
			$tree = LCP.parser(code, option);
		} catch (e) {
			$recentError = e;
			$tree = null;
		} finally {
			finishTime = Date.now();
		}

		return function (callback) {
			callback($recentError, $tree);
		};
	};
	return {
		parse: parse,
		lastParse: function () {
			return {
				code: sourceCache,
				t: finishTime
			};
		},
		setup: LC.setup,
		getCase: function (param, dictionary, option) {
			var dict;
			try {
				dict = new LD(dictionary);
			} catch (e) {
				dict = undefined;
			}
			//it's code
			if (angular.isString(param)) {
				var $cp = null, error = null;
				parse(param, option)(function (err, ast) {
					if (!err) {
						$cp = LC.Case(ast, dict);
					}
					error = err;
				});

				return function (callback) {
					callback(error, $cp);
				};
			}
			//it's a syntax tree
			return LC.Case(param, dict);
		},
		$debugInternal: function () {
			return {
				LC:LC,
				p:LCP,
				t: finishTime,
				e: $recentError,
				ast: $tree
			};
		}
	};
});